"""
    舵机
"""
import time
from threading import Lock

from fastapi import APIRouter, FastAPI, HTTPException
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field, validator
from periphery import PWM


router = APIRouter(
    prefix='/servo',
    tags=['servo']
)

# 创建锁对象
pwm_lock = Lock()


class SchemaIn(BaseModel):
    angle: int = Field(..., description="舵机转动的角度")
    @validator("angle")
    def check_angle(cls, v):
        if not 0 <= v <= 180:
            raise ValueError("角度必须在 0 到 180 之间")
        return v


@router.post("/", summary='舵机控制')
def servo_control(data: SchemaIn):
    angle = data.angle

    while pwm_lock:
        try:
            pwm = PWM(2, 0)
            pwm.frequency = 50  # 50Hz
            pwm.duty_cycle = 0.075  # 初始占空比
            # 启动 PWM
            pwm.enable()

            duty_cycle = (0.025 + (angle / 180.0) * 0.1)
            pwm.duty_cycle = duty_cycle
            time.sleep(0.5)
            return {"message": f"舵机已设置为 {angle} 度"}
        except Exception as e:
            raise HTTPException(status_code=400, detail=f"舵机控制失败: {str(e)}")
        finally:
            try:
                pwm.disable()
                pwm.close()
            except Exception as cleanup_error:
                print(f"PWM 清理失败: {cleanup_error}")


